package com.game.server;

import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

import com.game.bean.User;
import com.game.game.Game;
import com.game.share.Global;

public class GameThread implements Runnable {

	boolean isClose;

	ArrayList<Game> waitList;
	CopyOnWriteArrayList<Game> runningList;

	public GameThread() {
	}

	public void init() {
		isClose = false;
		waitList = new ArrayList<Game>();
		runningList = new CopyOnWriteArrayList<Game>();
	}

	public void close() {
		isClose = true;
	}

	public ArrayList<Game> getList() {
		return waitList;
	}

	@Override
	public void run() {
		while (!isClose) {
			long time = System.currentTimeMillis() + Global.GAME_TICKER;
			for (Game game : runningList) {
				game.run();
			}
			long deltaTime = System.currentTimeMillis() - time;
			if (deltaTime > 0) {
				try {
					Thread.sleep(deltaTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				System.out
						.println("game ticker is too short, cup can't follow");
			}
		}
	}

	public Game createGame(User user) {
		Game game = new Game();
		game.create(user);
		waitList.add(game);
		return game;
	}

	public void startGame(Game game, User user) {
		waitList.remove(game);
		runningList.add(game);
		game.Start(user);
	}

	public void removeGame(Game game) {
		if (waitList.contains(game)) {
			waitList.remove(game);
		} else if (runningList.contains(game)) {
			runningList.remove(game);
		} else {
			System.out.println("remove game failed");
		}
	}

}
